package client

import (
	"context"
	"fmt"
	"log"
	"os"
	"os/signal"
	"syscall"
	"time"
	"xin-job/client/callback"
	"xin-job/client/executor"
	"xin-job/client/handler"
	"xin-job/client/registry"
	"xin-job/client/sconf"
	"xin-job/client/server"
	"xin-job/core/utils"
)

var instance = &XxlClient{
	clientServer: *server.GetInstance(),
}

type XxlClient struct {
	clientServer server.EmbedServer
}

func GetInstance() *XxlClient {
	return instance
}

func (c *XxlClient) Start() {
	sconf.ServerConf.Read()

	ip, err := utils.GetIP()
	if err != nil {
		panic("get ip err")
	}

	var address = fmt.Sprintf("http://%s:%d/", ip, sconf.ServerConf.Port)

	// 执行器注册
	registry.GetInstance().Start(sconf.ServerConf.AppName, address)
	// 回调器启动
	callback.GetInstance().Start()

	// 启动 client http 服务
	go c.clientServer.Start()

	stop := make(chan os.Signal, 1)
	signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)

	// 阻塞
	<-stop

	registry.GetInstance().Stop()
	callback.GetInstance().Stop()

	// 优雅地关闭服务器
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	if err := c.clientServer.Server.Shutdown(ctx); err != nil {
		log.Printf("Server Shutdown: %v", err)

	}
	log.Println("Server gracefully stopped")
}

func (c *XxlClient) AddHandler(h handler.Handler) {
	executor.GetInstance().AddHandler(h)
}
